package com.ruoyi.miniapp.service.impl;

import com.ruoyi.common.core.constant.BedConstants;
import com.ruoyi.common.core.utils.DateUtils;
import com.ruoyi.common.core.utils.bean.BeanUtils;
import com.ruoyi.common.core.web.domain.AjaxResult;
import com.ruoyi.common.security.utils.SecurityUtils;
import com.ruoyi.miniapp.domain.Bed;
import com.ruoyi.miniapp.domain.Department;
import com.ruoyi.miniapp.domain.Hospital;
import com.ruoyi.miniapp.domain.Order;
import com.ruoyi.miniapp.domain.vo.DeptVO;
import com.ruoyi.miniapp.domain.vo.HospitalVO;
import com.ruoyi.miniapp.domain.vo.OrderVO;
import com.ruoyi.miniapp.mapper.BedMapper;
import com.ruoyi.miniapp.mapper.OrderMapper;
import com.ruoyi.miniapp.service.IBedService;
import com.ruoyi.miniapp.service.IDepartmentService;
import com.ruoyi.miniapp.service.IHospitalService;
import com.ruoyi.miniapp.service.IOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 订单管理Service业务层处理
 *
 * @author ruoyi
 * @date 2022-10-23
 */
@Service
public class OrderServiceImpl implements IOrderService {
    @Resource
    private OrderMapper orderMapper;

    @Resource
    private BedMapper bedMapper;

    @Autowired
    private IBedService bedService;

    @Autowired
    private IDepartmentService departmentService;

    @Autowired
    private IHospitalService hospitalService;

    /**
     * 查询订单管理
     *
     * @param orderId 订单管理主键
     * @return 订单管理
     */
    @Override
    public Order selectOrderByOrderId(Long orderId) {
        return orderMapper.selectOrderByOrderId(orderId);
    }

    /**
     * 查询订单管理列表
     *
     * @param order 订单管理
     * @return 订单管理
     */
    @Override
    public List<Order> selectOrderList(Order order) {
        return orderMapper.selectOrderList(order);
    }

    /**
     * 新增订单管理
     *
     * @param order 订单管理
     * @return 结果
     */
    @Override
    public int insertOrder(Order order) {
        return orderMapper.insertOrder(order);
    }

    /**
     * 修改订单管理
     *
     * @param order 订单管理
     * @return 结果
     */
    @Override
    public int updateOrder(Order order) {
        return orderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单管理
     *
     * @param orderIds 需要删除的订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderIds(Long[] orderIds) {
        return orderMapper.deleteOrderByOrderIds(orderIds);
    }

    /**
     * 删除订单管理信息
     *
     * @param orderId 订单管理主键
     * @return 结果
     */
    @Override
    public int deleteOrderByOrderId(Long orderId) {
        return orderMapper.deleteOrderByOrderId(orderId);
    }

    @Override
    public AjaxResult createOrderFromLogin(String bedCode) {
        Bed bed = bedMapper.selectBedByBedCode(bedCode);
        if (ObjectUtils.isEmpty(bed)) {
            return AjaxResult.error(601, BedConstants.BED_NOT_FOUND);
        }
        if (bed.getStatus() == -1) {
            return AjaxResult.error(602, BedConstants.BED_DEAD);
        }
        if (bed.getStatus() == 1) {
            return AjaxResult.error(603, BedConstants.BED_BUSY);
        }
        if (bed.getStatus() == 2) {
            return AjaxResult.error(604, BedConstants.BED_EXCEPTION);
        }
        if (Integer.parseInt(bed.getBatteryLevel()) <= 20) {
            return AjaxResult.error(605, BedConstants.BED_LOW_BATTERY);
        }
        OrderVO orderVO = new OrderVO();
        //创建order并插入数据库
        Order order = new Order();
        order.setOrderNumber(UUID.randomUUID().toString());
        //订单状态:1进行中、2待支付 、3已支付、4已完成
        order.setOrderStatus(1L);
        order.setOrderTime(DateUtils.getNowDate());
        order.setBedId(bed.getBedId());
        order.setLoginId(SecurityUtils.getUserId());
        order.setStatus(1L);
        orderMapper.insertOrder(order);
        BeanUtils.copyBeanProp(orderVO, order);
        //修改床位状态为1（状态关机-1, 0闲，1忙，2异常）
        bed.setStatus(1L);
        bedService.updateBed(bed);
        Hospital hospital = hospitalService.selectHospitalByHospitalId(bed.getHospitalId());
        HospitalVO hospitalVO = new HospitalVO();
        BeanUtils.copyProperties(hospital, hospitalVO);
        Department department = departmentService.selectDepartmentByDeptId(bed.getDeptId());
        DeptVO deptVO = new DeptVO();
        BeanUtils.copyProperties(department, deptVO);
        hospitalVO.setDept(deptVO);
        orderVO.setUnitPrice(hospital.getRent());
        orderVO.setHospital(hospitalVO);
        return AjaxResult.success(orderVO);
    }

    @Override
    public List<Order> selectAllOrderFromLogin() {
        Long userId = SecurityUtils.getUserId();
        return null;
    }

    @Override
    public AjaxResult updateOrderToEnd(Long orderId) {
        Order order = selectOrderByOrderId(orderId);
        if (ObjectUtils.isEmpty(order)) {
            return AjaxResult.error("该订单不存在");
        }
        //订单状态:1进行中、2待支付 、3已支付、4已完成
        if (order.getOrderStatus() != 1) {
            return AjaxResult.error("订单状态异常,不可结束订单");
        }
        order.setOrderStatus(2L);
        order.setGiveBackTime(DateUtils.getNowDate());
        order.setLeaseTime(DateUtils.getDatePoor(order.getGiveBackTime(),order.getOrderTime()));
        Bed bed = bedService.selectBedByBedId(order.getBedId());
        //修改床位状态为0（状态关机-1, 0闲，1忙，2异常）
        bed.setStatus(0L);
        bedService.updateBed(bed);
        Hospital hospital = hospitalService.selectHospitalByHospitalId(bed.getHospitalId());
        order.setRent(countRentNum(order.getOrderTime(),order.getGiveBackTime(),hospital.getRent()));
        orderMapper.updateOrder(order);
        return AjaxResult.success("您的订单已生成，请前往支付页面进行支付");
    }

    @Override
    public AjaxResult payOrder(Long orderId) {
        Order order = orderMapper.selectOrderByOrderId(orderId);
        order.setPaymentTime(DateUtils.getNowDate());
        order.setOrderStatus(3L);
        int rows = updateOrder(order);
        return rows > 0 ? AjaxResult.success("支付成功"):AjaxResult.error("支付失败");
    }

    @Override
    public List<Order> selectAllOrderPersonal(Long status) {
        Order orderTemp = new Order();
        orderTemp.setOrderStatus(status);
        List<Order> orderList = selectOrderList(orderTemp);
        return orderList.stream().filter(order -> order.getLoginId().equals(SecurityUtils.getUserId())).collect(Collectors.toList());
    }

    @Override
    public OrderVO getOrderDetail(Long orderId) {
        OrderVO orderVO = new OrderVO();
        Order order = selectOrderByOrderId(orderId);
        BeanUtils.copyProperties(order, orderVO);
        Bed bed = bedService.selectBedByBedId(order.getBedId());
        BeanUtils.copyProperties(bed, orderVO);
        Hospital hospital = hospitalService.selectHospitalByHospitalId(bed.getHospitalId());
        Department department = departmentService.selectDepartmentByDeptId(bed.getDeptId());
        DeptVO deptVO = new DeptVO();
        HospitalVO hospitalVO = new HospitalVO();
        hospitalVO.setDept(deptVO);
        orderVO.setHospital(hospitalVO);
        BeanUtils.copyProperties(hospital, hospitalVO);
        BeanUtils.copyProperties(department, deptVO);
        orderVO.setUnitPrice(hospital.getRent());
        return orderVO;
    }

    private BigDecimal countRentNum(Date start, Date end, BigDecimal unitPrice) {
        if (start.after(end)) {
            return new BigDecimal(-1);
        }
        long timeDiff = start.getTime() - end.getTime();
        long hour = timeDiff / 1000 / 60 / 60;
        BigDecimal hours = new BigDecimal(Long.toString(hour));
        return hours.multiply(unitPrice);
    }
}
